package com.tencent.cloud.iov.recycler.flow;

import android.app.Activity;
import android.support.annotation.CallSuper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.tencent.cloud.iov.flow.view.impl.BaseFlowView;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.flow.presenter.IPresenter;
import com.tencent.cloud.iov.recycler.block.BlockLayoutManager;
import com.tencent.cloud.iov.recycler.block.BlockRecyclerAdapter;
import com.tencent.cloud.iov.recycler.block.BlockRecyclerView;
import com.tencent.cloud.iov.recycler.block.BlockSpanSizeLookup;
import com.tencent.cloud.iov.recycler.item.IBlockItem;

import java.util.List;

/**
 * @author showxiao
 * @date 2018/5/3
 */

public abstract class BaseRecyclerFlowView<P extends IPresenter> extends BaseFlowView<P>
        implements RecyclerContract.View {

    private RecyclerView mRecyclerView;
    private BlockRecyclerAdapter<IBlockItem> mRecyclerAdapter;

    public BaseRecyclerFlowView(Activity activity) {
        super(activity);
    }

    public BaseRecyclerFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }

    @Override
    public void updateList(List<IBlockItem> item) {
        ensureRecyclerView();
        mRecyclerAdapter.swapData(item);
    }

    private void ensureRecyclerView() {
        if (mRecyclerView == null) {
            mRecyclerView = createRecyclerView();
            attachRecyclerView(mRecyclerView);
        }
    }

    @CallSuper
    protected RecyclerView createRecyclerView() {
        BlockRecyclerView recyclerView = new BlockRecyclerView(getContext());
        recyclerView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        mRecyclerAdapter = new BlockRecyclerAdapter<>(this);
        recyclerView.setAdapter(mRecyclerAdapter);

        BlockLayoutManager layoutManager = new BlockLayoutManager(getContext());
        layoutManager.setSpanSizeLookup(new BlockSpanSizeLookup(mRecyclerAdapter));
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setItemAnimator(null);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);

        return recyclerView;
    }

    protected void attachRecyclerView(View recyclerView) {
        setContentView(recyclerView);
    }
}
